/*
 * @Description: 
 * @Version: 2.0
 * @Autor: zouxuemiao
 * @Date: 2022-03-24 15:48:35
 * @LastEditors: zouxuemiao
 * @LastEditTime: 2022-03-28 19:37:41
 */

declare var require: NodeRequire
declare var module: NodeModule
var mockjs = require('mockjs')
var _ = require('lodash')
var express = require('express');
var router = express.Router();


// 源数据
type TItem = {
  id: number,
  content: string,
  state: number,
}

type TReObject = {
  [key: string]: any
}

// 假数据
let sourceData: TItem[] | undefined = [
  {
    id: 0,
    content: '做作业',  // list 的内容
    state: 0,   // 完成状态： 0 未完成， 1 已完成
  },
  {
    id: 1,
    content: '干饭',
    state: 0,
  },
  {
    id: 2,
    content: '睡觉',
    state: 1,
  },
]
let newSourceData: TItem[] = _.cloneDeep(sourceData)

// 筛选 ---> 0:全部，1 所有未完成， 2 所有已完成
const filterByState = (finishState: string) => {
  let searchResult

  switch (finishState) {
    case 'all':
      searchResult = newSourceData
      break;
    case 'undo':
      searchResult = newSourceData.filter((item: TItem) => {
        return item.state == 0
      })
      break;
    case 'done':
      searchResult = newSourceData.filter((item: TItem) => {
        return item.state == 1
      })
      break;
    default:
      break;
  }
  return searchResult
}


// 获取list  
router.get('/getList', (req: TReObject, res: TReObject) => {
  const filterResult = filterByState(req.query.finishState)

  res.json({
    data: filterResult,
    msg: 'ok'
  })
})



// 新增 list
router.post('/add', (req: TReObject, res: TReObject) => {
  // post -- req.body  , get -- query
  newSourceData.unshift({
    id: Date.now(),
    content: req.body.content,
    state: 0,
  })

  // 返回
  res.json({
    data: newSourceData,
    msg: '新增成功'
  })
});



// 编辑文本
router.post('/edit', (req: TReObject, res: TReObject) => {
  newSourceData = newSourceData.map((item: TItem) => {
    if(item.id == req.body.id) {
      item.content = req.body.newContent
    }
    return item
  })

  // 返回
  res.json({
    data: newSourceData,
    msg: '编辑成功'
  })
});


// 删除
router.post('/del', (req: TReObject, res: TReObject) => {
  const filterResult = filterByState(req.body.nowState)

  sourceData = filterResult && filterResult.filter((item: TItem) => {
    return item.id !== req.body.id
  })
  newSourceData = newSourceData.filter(item => {
    return item.id !== req.body.id
  })

  
  // 返回
  res.json({
    data: sourceData,
    msg: '删除成功'
  })
});


// 修改 list 完成状态 -- checkbox
router.post('/change', (req: TReObject, res: TReObject) => {
  console.log('接收到修改', req.body)

  newSourceData = newSourceData.map((item: TItem) => {
    if(item.id == req.body.id) {
      item.state = item.state == 1? 0 : 1
    }
    return item
  })

  const filterResult = filterByState(req.body.nowState)

  // 返回
  res.json({
    data: filterResult,
    msg: '修改成功'
  })
});



module.exports = router;
